package com.example.cdpbookstore.web.servlet;


import com.example.cdpbookstore.pojo.entity.Book;
import com.example.cdpbookstore.pojo.entity.CartItem;
import com.example.cdpbookstore.service.BookService;
import com.example.cdpbookstore.service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@WebServlet("/add-to-cart")
public class AddToCartServlet extends HttpServlet {

    /**
     * 根据产品编号查询购物车明细项
     */
    private CartItem getCartIemByProductId(List<CartItem> cart, Long bookId) {
        for (CartItem cartItem : cart) {
            if (cartItem.getBook().getId().equals(bookId)) {
                return cartItem;
            }
        }

        return null; // 未找到
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取产品编号
        Long id = Long.valueOf(request.getParameter("id"));

        // 从Session中获取当前购物车
        HttpSession session = request.getSession();
        List<CartItem> cart = (List<CartItem>) session.getAttribute("cart");
        CartItem cartItem = null;
        if (cart != null) { // 购物已存在
            cartItem = getCartIemByProductId(cart, id);
            if (cartItem != null) { // 已有购物车项，直接使用该项
                cartItem.setQuantity(cartItem.getQuantity() + 1); //数量加1
            }
        } else {//购物车为空
            cart = new ArrayList<>(); // 新建购物车
        }

        if (cartItem == null) { //购物车项未创建
            cartItem = new CartItem(); //新建购物车明细项

            BookService bookService = new BookServiceImpl();
            Book book = bookService.getById(id);

            cartItem.setBook(book);
            cartItem.setQuantity(1); // 默认为1

            cart.add(cartItem); //增加当前购物车项
            session.setAttribute("cart", cart);
        }

        response.sendRedirect("index.jsp"); //返回首页
    }
}
